import { useState, useEffect } from 'react';
import { List } from './list';
import { SearchPanel } from './searchPanel';
import * as qs from 'qs';
import { cleanObject, useDebounce, useMount } from '../../utils/index';

// 接口环境变量
const apiUrl = process.env.REACT_APP_API_URL;

export const ProjectList = () => {
  const [param, setParam] = useState({
    name: '',
    id: '',
  });
  const [fruits, setFruits] = useState([]);
  const [list, setList] = useState([]);

  // 使用 debounce 防抖函数
  const debounceParam = useDebounce(param, 200);

  // 页面加载完成请求一次，参数变化就请求
  useEffect(() => {
    console.log(`${param.id}--${param.name}`);
    // fetch(`${apiUrl}/fruits?name=${param.name}&personId=${param.id}`).then(
    fetch(`${apiUrl}/fruits?${qs.stringify(cleanObject(debounceParam))}`).then(
      async (res) => {
        if (res) {
          setList(await res.json());
        }
      }
    );
  }, [debounceParam]);

  // 下拉选项数据只加载一次
  useMount(() => {
    fetch(`${apiUrl}/fruitsList`).then(async (res) => {
      if (res) {
        setFruits(await res.json());
      }
    });
  });

  return (
    <>
      <SearchPanel
        fruits={fruits}
        list={list}
        param={param}
        setParam={setParam}
      ></SearchPanel>

      <List fruits={fruits} list={list} />
    </>
  );
};
